const request=require('../../util/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page:1,
    limit:8,
    keyword:'',
    list:[],
    sellists:{},//物料表,通过FItemID设置内部多个参数
    selnum:0,//已经加入库存的数量
    showSelList:false,//是否显示底部弹出层
    showSellists:[],//显示部分
    deleteTimer: null,
    showReceiveDialog: false, // 领取弹窗显示状态
    lastClickTime: 0,
    receiveQuantity: 0,           // 领取数量
    currentMaterial: {},          // 当前操作的物料
    currentFItemID: '',           // 当前物料ID
    inputFocusId: null,           // 当前获得焦点的输入框ID
    originalValue: {},            // 原始值记录
    flag: false,                  // 加载标志
    count: 0,                     // 总数
    isSelNum:false,               //是否展示选择批次列表
    sel_wu_liao:{},               //对应物料表
    sel_wu_liao_text:null,        //对应物料名
    selectedBatch: null,
    receiveQuantity: '',
    isSel_wu_liao_list:[],         //操作一个物料填进去一个信息 选择的物料表，存放  物料id，批次
    showDropdown: false,
    searchText: '',               // 搜索文本
    filteredStockList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getList()
  },

  getList(){
    var that = this
    var params = {
      page: that.data.page,//当前页码
      limit: this.data.limit,//是否完成
      keyword:this.data.keyword,//关键字范围
    }
    request.requestGet('order/get_material_list', params, "加载中",function (res) {
      console.log(res,"resssssss")
      if (res.status === 200) {
        let list = that.data.list
        res.data.data.map((item) =>{
          return item.t = false;
        })
        if (that.data.page == 1) {
          list = []
        }
        list = [...list, ...res.data.data]
        if (list.length < res.data.count ){
          that.setData({
            page: that.data.page + 1,
            flag:true
          })
        } else {
          that.setData({
            flag:false
          })
        }
        that.setData({
          list: list,
          count: res.data.count
        })
      }
      
      }, function (res) {
        console.log(res,"请求失败")
      },
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if(this.data.flag){
      this.setData({
        flag:false
      })
      this.getList(); // 疯狂的请求的方法
    }
  },

  onSearch(e){
    this.setData({
      flag:true
    })
    this.data.page = 1
    this.data.keyword = e.detail
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0
    })
    this.getList(e.detail)
  },

  submit(e){
    console.log(this.data.sellists,'======提交的材料')
  },


  showSel(e){
    var that = this
    this.setData({
      showSelList:!that.data.showSelList
    })
    console.log(this.data.showSellists,"======***")
    console.log(this.data.sel_wu_liao,"AAAAAAAAAA")
    // for(let i=0;i<this.data.showSellists.length;i++){
    //   this.data.showSellists[i].selText = 
    // }
    this.data.showSellists = this.data.showSellists.map(item => {
      const extraText = this.data.sel_wu_liao[item.FItemID]; // 根据 FItemID 获取表2的值
      return {
        ...item,
        extraText: extraText || '' // 插入新属性，如果不存在则为空字符串
      };
    });
    this.setData({
      showSellists:this.data.showSellists
    })
    console.log(this.data.showSellists,"新的表");
  },

  // 输入框变化事件
  onInputChange(e) {
    const fitemId = e.currentTarget.dataset.id;
    const inputValue = e.detail.value;
    if (inputValue === '' || inputValue === '-') {
      return; // 允许清空或输入负号
    }
  },

  // 输入框获得焦点
  onInputFocus(e) {
    const fitemId = e.currentTarget.dataset.id;
    const currentValue = this.getCurrentValue(fitemId);
    this.setData({
      inputFocusId: fitemId,
      [`originalValue[${fitemId}]`]: currentValue
    });
  },

  // 输入框失去焦点（确认输入）
  onInputBlur(e) {
    const fitemId = e.currentTarget.dataset.id;
    let inputValue = e.detail.value;
    if (inputValue === '' || inputValue === '-') {
      inputValue = '0';
    }
    let newValue = parseFloat(inputValue);
    
    if (isNaN(newValue)) {
      newValue = this.data.originalValue[fitemId] || 0;
      this.showToast('请输入有效数字');
    }
    
    // 限制范围
    if (newValue < 0) {
      newValue = 0;
      this.showToast('数量不能小于0');
    }
    if (newValue > 99) {
      newValue = 99;
      this.showToast('数量不能大于99');
    }
    newValue = Math.round(newValue * 100) / 100;
    this.updateStepperValue(fitemId, newValue);
    // 清除焦点记录
    this.setData({
      inputFocusId: null
    });
  },


  sureSel(e){
    const fitemId = e.currentTarget.dataset.id;
    const inputValue = this.data.sellists[fitemId] || 0;
  
    console.log('领取:', fitemId, '数量:', inputValue);
  
    // 处理领取逻辑
    let quantity = Number(inputValue);
    // if (isNaN(quantity) || quantity <= 0) {
    //   wx.showToast({
    //     title: '请输入有效数量',
    //     icon: 'none'
    //   });
    //   return;
    // }
    
    this.updateStepperValue(fitemId, quantity);
    if(quantity <= 0){
      wx.showToast({
        title: '已移除',
        icon: 'success'
      });
    }else{
      wx.showToast({
        title: '领取成功',
        icon: 'success'
      });
    }
    
  },

  // 获取当前值（处理各种情况）
  getCurrentValue(fitemId) {
    const value = this.data.sellists[fitemId];
    if (value === undefined || value === null) {
      return 0;
    }
    return parseFloat(value) || 0;
  },

  // 显示提示
  showToast(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 1500
    });
  },

  updateCalculations(tmpid, tmpNum) {
    // console.log(tmpid,"tmpidtmpid")
    // console.log(tmpNum,"tmpNumtmpNum")
    console.log(this.data.sel_wu_liao, "updateCalculations");
    if(tmpNum === 0){
      this.removeFromSellists(tmpid);
      delete this.data.sel_wu_liao[tmpid]
      console.log('删除')
    }
    console.log(this.data.sel_wu_liao, "updateCalculations11111111");

    this.setData({
      sel_wu_liao:this.data.sel_wu_liao
    })
    let selnum = 0
    for (let key in this.data.sellists) {
      selnum += this.getCurrentValue(key);
    }
    selnum = selnum.toFixed(1);
    this.setData({
      selnum: selnum
    })
    const newArray = this.data.list.filter(item => {
      return this.data.sellists.hasOwnProperty(item.FItemID) && this.getCurrentValue(item.FItemID) > 0;
    });
    console.log(newArray,"111newArraynewArray")

    
    this.setData({
      showSellists: newArray
      
      // isSel_wu_liao_list:newArray，
    })
    for(let i = 0;i<newArray.length;i++){
      this.setData({
        [`isSel_wu_liao_list[${newArray[i].FItemID}]`]: newArray[i]
      })
    }
   
    // let tmpkey = 
    for(let i = 0;i<newArray.length;i++){
      let key = newArray[i].FItemID
      this.setData({
        
      })
    }
    this.setData({
      // isSel_wu_liao_list:newArray
    })
    console.log(this.data.showSellists,"=======7869165")
    console.log(this.data.isSel_wu_liao_list,"=======986415631")
  },

  // 移除项
  removeFromSellists(FItemID) {
    console.log(FItemID,"FItemIDFItemID")
    // if (this.data.deleteTimer) {
    //   clearTimeout(this.data.deleteTimer);
    // }
    const newSellists = {...this.data.sellists};
    console.log(newSellists,"===1111111")
    delete newSellists[FItemID];

    // const newSellists1 = {...this.data.showSellists};
    // delete newSellists1[FItemID];
    const newTable = this.data.showSellists.filter(item => item.FItemID !== FItemID);
    this.setData({
      showSellists:newTable
    })
    console.log(newSellists,"===222222")
    console.log(this.data.showSellists,"showSellists")
      this.setData({ 
        // showSellists: newSellists,
        sellists: newSellists
      })
      console.log(this.data.showSellists,"=======333333333")
      console.log(this.data.sellists,"=======4444444444")
    
  },


  onReceive(e) {
    const fitemId = e.currentTarget.dataset.id;
    this.updateStepperValue(fitemId, 1);
    wx.showToast({
      title: '领取成功',
      icon: 'success',
      duration: 1000
    });
  },
  
  // 修改更新数值方法，确保处理0的情况
  updateStepperValue(fitemId, value) {
    console.log(fitemId,"fitemIdfitemId")

    this.setData({
      [`sellists[${fitemId}]`]: value
    }, () => {
      this.updateCalculations();
    });
    console.log(this.data.selectedBatch,"selectedBatchselectedBatch")
    let tmp = this.data.selectedBatch
    let tmpBool = false
    for(let i = 0;i<tmp.length;i++){
      if(tmp[i].FItenID === String(fitemId)){
        tmpBool = true
      }
    }
    let FBatchNo = this.data.selectedBatch.FBatchNo
    if(tmpBool === false){
      this.data.sel_wu_liao[fitemId] = FBatchNo
      // this.setData({
      //   sel_wu_liao_text:''
      // })
      for(let key in this.data.sel_wu_liao){
        console.log("Key:", key); // 输出: 123
       
        if(key === String(fitemId)){
          console.log("PPPPPPPPPPPP")
            // tmpText = this.data.sel_wu_liao[key]
          this.setData({
            sel_wu_liao_text:'请选择批号',
            // tmpaaa:true
          })
        }
      }
      console.log(this.data.sel_wu_liao_text,"AAAAAAAAA")
    }
  },

  showReceiveDialog(e) {
    console.log(e,'tanchu')
    const item = e.currentTarget.dataset.item;
    let tmpText = '请选择批号'
    console.log(this.data.sel_wu_liao,"ASANFILAHISL")
    this.setData({
      showReceiveDialog: true,
      currentMaterial: item,
      currentFItemID: item.FItemID,
      receiveQuantity: 1.0, // 重置为默认值1
      sel_wu_liao_text:tmpText,
      searchText:'',
      receiveQuantity:0,
    });
  },
  
  // 隐藏领取弹窗
  hideReceiveDialog() {
    this.setData({
      showReceiveDialog: false,
      currentFItemID: '',
      receiveQuantity: 0,
      searchText:''
    });
  },


  onReceiveQuantityChange(e) {
    const quantity = e.detail.value;
    this.setData({
      receiveQuantity: quantity
    });
  },

  confirmReceive(e) {
    const { currentFItemID, receiveQuantity } = this.data;
    if(receiveQuantity === 0){
      wx.showToast({
        title: '数量应>0',
        icon: 'none'
      });
      return;
    }
    if (!currentFItemID) {
      wx.showToast({
        title: '领取失败',
        icon: 'none'
      });
      return;
    }
    if(this.data.sel_wu_liao_text === '请选择批号'){
      wx.showToast({
        title: '请选择批次',
        icon: 'none'
      });
      return;
    }
    this.updateStepperValue(currentFItemID, receiveQuantity);
    this.hideReceiveDialog();
    
    wx.showToast({
      title: '领取成功',
      icon: 'success',
      duration: 1500
    },this.setData({
      receiveQuantity:0
    }));
  },


  onBatchChange(event) {
    const selectedValue = event.detail;
    let batchDetail = null;
    
    if (selectedValue) {
      batchDetail = this.data.batchOptions[selectedValue];
    }
    
    this.setData({
      selectedBatch: selectedValue,
      selectedBatchDetail: batchDetail
    });
  },

  sel_pi_ci(e){
    let tmp = this.data.isSelNum
    this.setData({
      isSelNum:!tmp
    })
  },


























  toggleDropdown() {
    this.setData({
      showDropdown: !this.data.showDropdown
    });
  },

  // 关闭下拉
  closeDropdown() {
    this.setData({
      showDropdown: false
    });
  },

  // 选择选项
  selectOption(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      selectedBatch: item,
      showDropdown: false
    });
    
    // 触发change事件
    this.onBatchChange(item);
  },

  // 批次选择变化回调
  onBatchChange(selectedBatch) {
    // let tmpStr = selectedBatch.FBatchNo+' | 库存:'+selectedBatch.FQty
    let tmpStr = selectedBatch.FBatchNo
    this.setData({
      sel_wu_liao_text:tmpStr
    })
    // 这里可以处理选择后的逻辑
  },


  onSearchInput(e) {
    console.log(e,"eeeeee")
    const searchText = e.detail.value;
    this.setData({
      searchText: searchText
    });
    this.filterStockList(searchText);
  },

  // 过滤批次列表
  filterStockList(searchText) {
    console.log(searchText,"searchTextsearchText")
    const { currentMaterial } = this.data;
    console.log(searchText,"searchTextsearchText")
    if (!searchText.trim()) {
      // 如果搜索框为空，显示所有批次
      this.setData({
        filteredStockList: currentMaterial.stockList
      });
      return;
    }

    // 过滤包含搜索文本的批次
    const filteredList = currentMaterial.stockList.filter(item => 
      item.FBatchNo.includes(searchText)
    );
    console.log(filteredList,"355555555")
    this.setData({
      filteredStockList: filteredList
    });
  },
  







  

})